
/**
 * Date:2019年6月3日上午9:22:46
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.client.handler;

import com.xue.im.client.core.IMClientContext;
import com.xue.im.common.IMUtil;
import com.xue.im.common.IMUtil.MessageType;
import com.xue.im.common.vo.Message;
import com.xue.im.common.vo.User;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Description: 登录请求处理 <br/>
 * Date: 2019年6月3日 上午9:22:46 <br/>
 * 
 * @author xuejianxin
 */
public class LoginAuthRequestHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Message message = IMUtil.buildMessage(MessageType.LOGIN_REQ);
		message.addOptions(IMUtil.USER_NAME, IMClientContext.get().getCurrentUser().getUserid())
				.addOptions(IMUtil.PASSWORD, IMClientContext.get().getCurrentUser().getPassword());
		// 发送握手请求消息, 构建登录请求消息
		ctx.writeAndFlush(message);
		//System.out.println("***client send login to server->:" + message);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Message message = (Message) msg;
		// System.out.println("LoginAuthRequestHandler: " + message);
		// 判断是否握手消息
		if (IMUtil.checkMessageType(message, MessageType.LOGIN_RESP)) {
			// 获取用户信息
			User logUser = (User) message.getBody();
			if (null == logUser) {// 验证是否登录成功
				ctx.close();
			} else {// 登录成功
				ctx.fireChannelRead(msg);
			}
		}
		else {
			// 否则收到不到其他消息
			ctx.fireChannelRead(msg);
		}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause);
	}

}
